#include "graphics/texturemanager.h"
#include "graphics/texture.h"
#include "graphics/graphicsmanager.h"
#include "graphics/renderer.h"

namespace dw
{
namespace graphics
{

ITexture* TextureManager::getTexture(const std::string& filename)
{
	TextureNameMap::iterator it = _texturesByName.find(filename);

	if (it == _texturesByName.end())
		return 0;
	else return it->second;
}

ITexture* TextureManager::loadTexture(const std::string& filename)
{
	if (filename.empty()) return 0; //throw std::invalid_argument(__FUNCTION__);

	TextureNameMap::iterator it = _texturesByName.find(filename);

	if (it == _texturesByName.end())
	{
		std::string texturePath = /*_rootPath +*/ "./" + filename;
		// if (!system::find_file(_rootPath, filename, texturePath)) throw std::invalid_argument("File not found : " + filename);
		ITexture* texture = GraphicsManager::getInstance().getRenderer().createTexture();
		texture->loadFromFile(texturePath);
		_texturesByName.insert(std::make_pair(filename, texture));
		return texture;
	}
	else return it->second;
}

void TextureManager::unloadTexture(const std::string& filename)
{
	if (filename.empty()) throw std::invalid_argument(__FUNCTION__);

	TextureIterator it = _texturesByName.find(filename);
	if (it != _texturesByName.end())
	{
		it->second->dispose();
		_texturesByName.erase(it);
	}
}

void TextureManager::unloadAll()
{
	for (TextureIterator it = _texturesByName.begin(); it != _texturesByName.end(); ++it)
		it->second->dispose();
	_texturesByName.clear();
}

} // namespace graphics
} // namespace dw
